const schema = require("../dao/roomSchema");
const userSchema = require("../dao/userSchema");
const chatSchema = require("../dao/chatSchema");

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

function createRoom(name, creatorId, cb) {
    let room = new schema({
        name: name
    });
    room.members.push(creatorId);
    let saveRoom = room.save(),
        findUser = userSchema.findById(creatorId);

    Promise.all([saveRoom, findUser]).then(res => {
        res[1].rooms.push(res[0]._id);
        // console.log(res[0]);
        res[1]
            .save()
            .then(() => {
                cb({ message: "添加房间成功", ok: true, data: res[0] });
            })
            .catch(err => {
                cb({ message: "添加房间失败", ok: false, data: err });
            });
    });
}

function addMember(roomId, memberId, cb) {
    let findRoom = schema.findById(roomId),
        findUser = userSchema.findById(memberId);
    Promise.all([findRoom, findUser])
        .then(res => {
            if (res[1] != null && !res[0].members.contains(res[1])) {
                res[0].members.push(memberId);
                let saveRoom = res[0].save();
                res[1].rooms.push(roomId);
                let saveUser = res[1].save();
                Promise.all([saveRoom, saveUser]).then(data => {
                    cb({ message: "添加房间成员成功", ok: true, data: data });
                });
            } else {
                cb({
                    message: "添加房间成员失败",
                    ok: false,
                    data: "不存在该成员或该成员重复"
                });
            }
        })
        .catch(err => {
            console.log(err);
            cb({ message: "添加房间成员失败", ok: false, data: err });
        });
}

function findUserRooms(userId, cb) {
    userSchema
        .findById(userId)
        .populate("rooms")
        .exec()
        .then(res => {
            cb({ message: "查找房间成功", ok: true, data: res.rooms });
        })
        .catch(err => {
            console.log(err);
            cb({ message: "查找房间失败", ok: false, data: err });
        });
}

function enterRoom(roomId, cb) {
    // themeModel.populate(theme, [
    //     { path: "posts.user", select: "name" },
    //     { path: "posts.comments.from", select: "name" },
    //     { path: "posts.comments.to", select: "name" }
    // ]);
    schema
        .findById(roomId)
        .populate({
            path: "chats",
            populate: { path: "from", select: { password: 0, rooms: 0 } }
        })
        .exec()
        .then(res => {
            cb({ message: "进入房间成功", ok: true, data: res });
        })
        .catch(err => {
            console.log(err);
            cb({ message: "进入房间失败", ok: false, data: err });
        });
}

module.exports = {
    create: createRoom,
    addMember: addMember,
    findUserRooms: findUserRooms,
    enter: enterRoom
};
